Micron Document
Livres et Wikis | Archives | Info


JavaScript syntax
part 27/43 Β· 161.3 KB total
layout: Wide Β· Narrow Β· Centered
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
console.log(Boolean(this) === true);
console.log(Boolean({}) === true);
console.log(Boolean([]) === true);
// These types return false
console.log(Boolean(null) === false);
console.log(Boolean(undefined) === false); // equivalent to Boolean()

The NOT operator evaluates its operand as a Boolean and returns the
negation. Using the operator twice in a row, as a double negative,
explicitly converts an expression to a primitive of type Boolean:

console.log( !0 === Boolean(!0));
console.log(Boolean(!0) === !!1);
console.log(!!1 === Boolean(1));
console.log(!!0 === Boolean(0));
console.log(Boolean(0) === !1);
console.log(!1 === Boolean(!1));
console.log(!"" === Boolean(!""));
console.log(Boolean(!"") === !!"s");
console.log(!!"s" === Boolean("s"));
console.log(!!"" === Boolean(""));
console.log(Boolean("") === !"s");
console.log(!"s" === Boolean(!"s"));

The ternary operator can also be used for explicit conversion:

console.log([] == false); console.log([] ? true : false); // β€œtruthy”,
but the comparison uses [].toString()
console.log([0] == false); console.log([0]? true : false); //
[0].toString() == "0"
console.log("0" == false); console.log("0"? true : false); // "0" β†’ 0
... (0 == 0) ... 0 ← false
console.log([1] == true); console.log([1]? true : false); //
[1].toString() == "1"
console.log("1" == true); console.log("1"? true : false); // "1" β†’ 1 ...
(1 == 1) ... 1 ← true
console.log([2] != true); console.log([2]? true : false); //
[2].toString() == "2"
console.log("2" != true); console.log("2"? true : false); // "2" β†’ 2 ...
(2 != 1) ... 1 ← true

Expressions that use features such as post–incrementation (i++) have an
anticipated side effect. JavaScript provides short-circuit evaluation of
expressions; the right operand is only executed if the left operand does
not suffice to determine the value of the expression.

console.log(a || b); // When a is true, there is no reason to evaluate
b.
console.log(a && b); // When a is false, there is no reason to evaluate
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────